home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: netcom.com!marnold
- From: marnold@netcom.com (Matt Arnold)
- Subject: Re: Constructor member initializer list
- Message-ID: <marnoldDpHEuD.EGy@netcom.com>
- Organization: NETCOM On-line Communication Services (408 261-4700 guest)
- References: <4jua8k$fa1$2@mhadg.production.compuserve.com>
- Date: Sun, 7 Apr 1996 07:44:37 GMT
- Sender: marnold@netcom19.netcom.com
-
- Alan Huff <74312.2300@CompuServe.COM> writes:
-
- >How do you initialize class members in the initializer list if the
- >member is a structure?
-
- >Consider the following code fragment.
-
- >typedef struct _tagRect {
- > int x;
- > int y;
- > int w;
- > int h;
- >} RECTANGLE;
-
- This style of struct declaration is not necessary is C++. The following
- will do...
-
- struct RECTANGLE {
- int x;
- int y;
- int w;
- int h;
- };
-
- In C++, structs are equivalent to classes, except everything defaults
- to public. structs can even have member functions, etc..
-
- The typedef and _tagRect nonsense is not needed in C++.
-
- >class Foo {
- > Foo() : <how do I initialize fooRect and it's members> {};
- > RECTANGLE fooRect;
- >};
-
- >Any suggestions would be greatly appreciated.
-
- Give RECTANGLE a constructor that takes four parameters to intialize x,
- y, w and h with...
-
- struct RECTANGLE {
- int x;
- int y;
- int w;
- int h;
-
- RECTANGLE(int X, int Y, int W, int H): x(X), y(Y), w(W), h(H) { }
- };
-
- ...and then you'll be able to write Foo like so...
-
- class Foo {
- Foo(): fooRect(1, 2, 3, 4) { }
- RECTANGLE fooRect;
- };
-
- If RECTANGLE must be declared "C-style", as you showed above (because
- it's also used with C code in your project, for example, or part of
- some C library you are using) and so can't give it a constructor or
- other member functions, you'll have to intialize fooRect outside of
- Foo's intializer list...
-
- class Foo {
- Foo() {
- fooRect.x = 1;
- fooRect.y = 2;
- fooRect.w = 3;
- fooRect.h = 4;
- }
- RECTANGLE fooRect;
- };
-
- You can only intialize types that have constructors in an intializer
- list.
-
- Regards,
- -------------------------------------------------------------------------
- Matt Arnold | | ||| | |||| | | | || ||
- marnold@netcom.com | | ||| | |||| | | | || ||
- Boston, MA | 0 | ||| | |||| | | | || ||
- 617.389.7384 (h) 617.576.2760 (w) | | ||| | |||| | | | || ||
- C++, MIDI, Win32/95 developer | | ||| 4 3 1 0 8 3 || ||
- -------------------------------------------------------------------------
-